package com.gin.kotlin.gf2gamecommunity.routes

import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.rounded.Home
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import com.gin.kotlin.form.CommentForm
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.composable.ConfirmDialog
import com.gin.kotlin.gf2gamecommunity.composable.ComplaintDialog
import com.gin.kotlin.gf2gamecommunity.composable.ReplyFAB
import com.gin.kotlin.gf2gamecommunity.navi.GF2Navigator
import com.gin.kotlin.gf2gamecommunity.viewmodel.CommentListViewModel
import com.gin.kotlin.gf2gamecommunity.viewmodel.UserViewModel
import com.gin.kotlin.response.comment.CommentInfo
import kotlinx.coroutines.delay
import kotlinx.serialization.Serializable


fun NavGraphBuilder.commentSingle(navigator: GF2Navigator) = composable<CommentSingleRoute>(
    // 从屏幕右侧进入，持续500毫秒
    enterTransition = { slideInHorizontally(tween(500)) { it } },
    // 从屏幕右侧退出，持续500毫秒
    exitTransition = { slideOutHorizontally(tween(500)) { it } },
) {
    CommentSingleComposable(navigator = navigator, route = it.toRoute())
}

@Serializable
data class CommentSingleRoute(
    val topicTitle: String = "",
    var topicId: Int,
    var commentId: Int,
) {
    fun toForm() = CommentForm(topicId, commentId)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CommentSingleComposable(route: CommentSingleRoute, userViewModel: UserViewModel = viewModel(), navigator: GF2Navigator, viewModel: CommentListViewModel = viewModel()) {
    navigator.apply {
        val state = viewModel.floorInfo.fetch(route.toForm()).observeAsState()
        val onClickImage: (item: CommentInfo, url: String) -> Unit = { item, url -> onNavigateToImagePreView(ImagePreViewRoute(url, item.picList ?: listOf(url))) }

        var showDeleteDialog by remember { mutableStateOf(false) }
        var commentIdToDelete by remember { mutableIntStateOf(0) }

        var showComplaintDialog by remember { mutableStateOf(false) }
        var complaintTarget = CommentInfo()

        userViewModel.cUser.fetch()
        val userInfoState = userViewModel.cUser.liveData.observeAsState()

        // 如果发帖flag为true，说明刚刚成功发布了回复需要更新当前数据
        if (App.INSTANCE.replyFlag) {
            App.INSTANCE.replyFlag = false
            LaunchedEffect(Unit) {
                delay(1000)
                viewModel.floorInfo.fetch(route.toForm(), true)
            }
        }

        Scaffold(
            topBar = {
                TopAppBar(navigationIcon = {
                    IconButton(onClick = { onPopBackStack() }) {
                        Icon(imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "后退")
                    }
                }, actions = {
                    IconButton(onClick = {
                        onNavigateToCommentList(CommentListRoute(route.topicId))
                    }) {
                        Icon(Icons.Rounded.Home, contentDescription = "跳转到主楼")
                    }
                 IconButton(onClick = {
                        viewModel.floorInfo.fetch(route.toForm(), true)
                    }) {
                        Icon(imageVector = Icons.Filled.Refresh, contentDescription = "刷新")
                    }
                }, title = {
                    Text(route.topicTitle)
                })
            },
            floatingActionButton = {
                ReplyFAB(ReplyRoute(route.topicId, commentId = route.commentId), onNavigateToReply = { onNavigateToReply(it) }, onRefresh = {
                    viewModel.floorInfo.fetch(route.toForm(), true)
                })
            }

        ) { paddingValues ->
            val modifier = Modifier.padding(paddingValues)
            state.value?.data?.also { info ->
                // 数据结构展开为列表
                val items = info.let {
                    val list = mutableListOf(it)
                    it.commentReply?.also { i -> list.addAll(i) }
                    list
                }


                LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = modifier
                    .fillMaxSize()
                    .padding(4.dp)) {
                    itemsIndexed(items = items) { index, item ->
                        if (index == 0) {
                            CommentItem(info,
                                topicId = route.topicId,
                                onConfirmDeleteComment = { commentId ->
                                    showDeleteDialog = true
                                    commentIdToDelete = commentId
                                },
                                showCommentReply = false,
                                onClickImage = onClickImage,
                                onNavigateToUserCenter = { onNavigateToUserCenter(it) },
                                onNavigateToReply = { onNavigateToReply(ReplyRoute(route.topicId, it)) },
                                onComplaint = { info ->
                                    complaintTarget = info
                                    showComplaintDialog = true
                                }
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                            HorizontalDivider()
                            Spacer(modifier = Modifier.height(20.dp))
                        } else {
                            SubCommentItem(
                                item = item,
                                index = index,
                                userInfoState = userInfoState,
                                onClickImage = onClickImage,
                                onNavigateToUserCenter = { onNavigateToUserCenter(it) },
                                onConfirmDeleteComment = { commentId ->
                                    showDeleteDialog = true
                                    commentIdToDelete = commentId
                                },
                                onNavigateToReply = { onNavigateToReply(ReplyRoute(route.topicId, route.commentId, it)) },
                            )

                        }
                    }
                }
            } ?: Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                CircularProgressIndicator()
            }
        }

        if (showDeleteDialog) {
            ConfirmDialog(onDismissRequest = { showDeleteDialog = false },
                onConfirmation = {
                    viewModel.remove(topicId = route.topicId, commentId = commentIdToDelete) {
                        showDeleteDialog = false
                        viewModel.floorInfo.fetch(route.toForm(), true)
                    }
                }) {
                Text("确认删除该回复?")
            }
        }

        if (showComplaintDialog) {
            ComplaintDialog(route.topicId, complaintTarget, onDismissRequest = { showComplaintDialog = false })
        }
    }
}